package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"hema-fresh/hemarpc/models/cache"
	"hema-fresh/hemarpc/models/mysql"
	"time"

	"hema-fresh/hemarpc/hemarpc"
	"hema-fresh/hemarpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProductListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewProductListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProductListLogic {
	return &ProductListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 列表
func (l *ProductListLogic) ProductList(in *hemarpc.ProductListRequest) (*hemarpc.ProductListResponse, error) {
	// todo: add your logic here and delete this line
	var list []*hemarpc.ProductList
	var err error
	key := fmt.Sprintf("hemaList_%s", in)
	result, _ := cache.Rdb.Get(l.ctx, key).Result()
	if result == "" {
		if list, err = mysql.ProductList(mysql.DB, in); err != nil {
			return nil, err
		}
		marshal, _ := json.Marshal(list)
		cache.Rdb.Set(l.ctx, key, marshal, time.Minute*30)
	} else {
		json.Unmarshal([]byte(result), &list)
	}

	return &hemarpc.ProductListResponse{
		List: list,
	}, nil
}
